package com.breeze.jetpackproject.livedata;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.arch.core.util.Function;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.Transformations;

import com.breeze.jetpackproject.R;

public class Demo1Activity extends AppCompatActivity {
    private static final String TAG = "Demo1Activity";
    MutableLiveData<String> nameLiveData = new MutableLiveData<>();

    MutableLiveData<String> mutableLiveData = new MutableLiveData<>();
    MutableLiveData<String> mutableLiveData1 = new MutableLiveData<>();
    MutableLiveData<String> mutableLiveData2 = new MutableLiveData<>();
    MutableLiveData<Integer> liveDataSwitch = new MutableLiveData<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo1);
        // 1. observer演示
        nameLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String name) {
                Log.i(TAG, "onChanged: newName=" + name);
            }
        });
        // 2. Transformations.map演示
        LiveData<String> map = Transformations.map(nameLiveData, new Function<String, String>() {
            @Override
            public String apply(String input) {
                String newStr = input + " wang";
                Log.i(TAG, "apply: retrun " + newStr);
                return newStr;
            }
        });
        map.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.i(TAG, "onChanged: finalName=" + s);
            }
        });


        // 3. Transformations.switchMap演示
        LiveData<String> stringLiveData = Transformations.switchMap(liveDataSwitch, new Function<Integer, LiveData<String>>() {
            @Override
            public LiveData<String> apply(Integer input) {
                switch (input) {
                    case 1:
                        return mutableLiveData1;
                    case 2:
                        return mutableLiveData2;
                    default:
                        return mutableLiveData;
                }
            }
        });
        stringLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.i(TAG, "onChanged: " + s);
            }
        });
    }

    public void getNewName(View view) {
        String name = "breeze";
        nameLiveData.setValue(name);

        liveDataSwitch.setValue(1);
        mutableLiveData.setValue("a");
        mutableLiveData1.setValue("b");
        mutableLiveData2.setValue("c");
    }
}